<?php

class IndexController extends Zend_Controller_Action {

    public function indexAction() {
        $config = Zend_Registry::get('config');
        $layout = $this->_helper->layout();
        $model = new PageModel();
        $snippets = new SnippetModel();
        $addons = new AddonsModel();
        $mods = $model->getAddonsList('page', 'title');
        $pages_tree = Zend_Registry::get('pages');
        $this->view->modules = $mods;
        $this->view->pages = $pages_tree;


        if (WAY == 'ajax') {
            $sid = (int) $this->getRequest()->getParam('sid', 0);
            $section = $model->getSection($sid);
            $sections[] = $section;
            define('PAGE_ID', $section->pid);
            $page = $pages_tree[PAGE_ID];
            if ($page->acl < 1)
                exit;
            $layout->disableLayout();
        } elseif (WAY == 'admin') {
            $t = Zend_Registry::get('Zend_Locale');
            $this->view->navigation_line = array($t->_('Start page') => ADMIN_URL . '/');
            $session = new Zend_Session_Namespace('UnCMS');
            if (USER_ID == 0 || !$session->acl) {
                $this->_redirect(ADMIN_URL . '/acl/login');
            } else {
                $this->_forward('index', 'pages');
                return;
            }
        } else {
            $page = $model->getPageByURL(htmlentities($_SERVER["REQUEST_URI"]));
        }

        if (isset($page->id)) {

            if ($page->acl < 1 || $page->visible > 2)
                $page = $this->view->pages[$config->page404];
            if ($page->template > 0) {
                $template = $model->getAddons('template', $page->template);
                $templateTitle = $template->title;
            } else {
                $templateTitle = $config->template;
            }

            $this->view->setScriptPath(APP_PATH . '/templates/' . $templateTitle . '/scripts');

            if (isset($_GET['print_version']) && $_GET['print_version'] == '1') {
                $layout->setLayout('print');
            } elseif (file_exists(APP_PATH . '/templates/' . $templateTitle . '/layouts/index.phtml')) {
                $layout->setLayoutPath(APP_PATH . '/templates/' . $templateTitle . '/layouts');
                define('TEMPLATE', $config->url . '/templates/' . $templateTitle);
            } else {
                $layout->setLayoutPath(APP_PATH . '/templates/site/layouts');
                define('TEMPLATE', $config->url . '/templates/site');
            }

            $this->view->page = $page;
            $this->view->page_description = $page->description;
            $this->view->page_keywords = $page->keywords;
            $this->view->page_title = $page->title;
            $this->view->t = $addons->getTranslate($page->lang);

            if (!defined('PAGE_ID'))
                define('PAGE_ID', $page->id);
            define('PAGE_TITLE', $page->title);
            define('PAGE_DESCRIPTION', $page->description);
            define('PAGE_KEYWORDS', $page->keywords);
            define('PAGE_URL', $page->url);
            define('PAGE_ACL', $page->acl);
            define('TEMPLATE_TITLE', $templateTitle);
        } else {
            exit;
        }

        if (PAGE_ID == $config->page404)
            $this->getResponse()->setHttpResponseCode(404);

        if (WAY <> 'ajax')
            $sections = $model->getSections(PAGE_ID);

        for ($i = 0; $i <= 20; $i++)
            $block[] = null;

        $cache = Zend_Registry::get('Zend_Cache');
        $index_me = true;
        foreach ($sections as $key => $val) {
            $bid = $val->bid;
            $this->view->section = $val;
            $controller = ucfirst($mods[$val->mid]) . 'Controller';
            $modelName = ucfirst($mods[$val->mid]) . 'Model';
            if ($modelName == 'SearchModel')
                $index_me = false;
            $request = $this->getRequest()->setParam('sid', $val->id);
            $cacheIdentifier = '';
            if (method_exists($modelName, 'getCacheIdentifier')) {
                $model = new $modelName();
                $cacheIdentifier = $model->getCacheIdentifier($request);
            }
            $addons->addTranslate($mods[$val->mid], $page->lang);

            //Проверка на кэшэрность
            if ($cacheIdentifier == '' || !($content = $cache->load($val->id . $cacheIdentifier))) {
                $action = new $controller($request, $this->getResponse(), array('sid' => $val->id));
                $run = $action->indexAction();
                if ($mods[$val->mid] <> 'picker') {
                    if ($val->sid <> 0) {
                        $snip = $snippets->getSnip($val->id);
                        if (!file_exists(APP_PATH . '/templates/snippets/' . $snip->file . '.phtml')) {
                            $content = '';
                        } else {
                            $this->view->setScriptPath(APP_PATH . '/templates/snippets');
                            $content = $action->view->render($snip->file . '.phtml');
                        }
                    } else {
                        if (!file_exists(APP_PATH . '/templates/' . TEMPLATE_TITLE . '/scripts/' . $mods[$val->mid] . '/index.phtml')) {
                            $this->view->setScriptPath(APP_PATH . '/templates/site/scripts');
                        } else {
                            $this->view->setScriptPath(APP_PATH . '/templates/' . TEMPLATE_TITLE . '/scripts');
                        }
                        $content = $action->view->render($mods[$val->mid] . '/index.phtml');
                    }
                } else {
                    $content = $run;
                }
                if ($cacheIdentifier <> '' && $config->etrace <> 1)
                    $cache->save($content);
            }
            $block[$bid] .= $content;
        }

        //Индексирование при отсутствии существующего индекса
        if ($index_me && $config->etrace == 0) {
            $full_url = $_SERVER["REQUEST_URI"];
            if (!file_exists(APP_PATH . '/index')) {
                mkdir(APP_PATH . '/index');
                $index = Zend_Search_Lucene::create(APP_PATH . '/index');
            } else {
                $index = Zend_Search_Lucene::open(APP_PATH . '/index');
            }
            $hits = $index->find('url:' . $full_url);
            if (count($hits) == 0) {
                Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
                $doc = Zend_Search_Lucene_Document_Html::loadHTML($block[0],true, 'UTF-8');
                $doc->addField(Zend_Search_Lucene_Field::Text('url', $full_url));
                $doc->addField(Zend_Search_Lucene_Field::Text('page_url', $page->url));
                $doc->addField(Zend_Search_Lucene_Field::Text('page_id', $page->id));
                $doc->addField(Zend_Search_Lucene_Field::UnIndexed('page_title', $this->view->page_title));
                //$doc->addField(Zend_Search_Lucene_Field::Text('content', strip_tags($block[0]), 'UTF-8'));
                $index->addDocument($doc);
            }
        }

        if (WAY == 'ajax') {
            echo $content;
        } else {
            $this->_helper->layout()->block = $block;
        }
        $this->_helper->viewRenderer->setNoRender(true);
    }

}